import {
    observable,
    action,
    computed,
    runInAction,
    toJS
} from 'mobx';

import BaseStore from '../BaseStore';
import validationUtil from '@/utils/validation';
import {
    noticeMessage
} from '@utils/common-message';

class Store extends BaseStore {
    @observable enterpriseInfo;
    @observable name;
    @observable address;
    @observable creditCode;
    @observable mainBusiness;
    @observable creditCodeFile;
    @observable creditCodeFileList;
    @observable empowermentCodeFile;
    @observable empowermentCodeFileList;
    @observable previewImageUrl;
    @observable errMsg = {
        name: '',
        address: '',
        creditCode: '',
        mainBusiness: '',
        creditCodeFile: '',
        empowermentCodeFile: '',
    };
    isSuccess = false;
    globalErrMsg = '';

    @observable provinceData;
    @observable province_code;
    @observable province_name;
    @observable cityData;
    @observable city_code;
    @observable city_name;
    @observable districtData;
    @observable district_code;
    @observable district_name;
    @computed
    get provinces() {
        let data = {
            code: '-1',
            name: '请选择'
        };
        return this.provinceData ? [
            data,
            ...toJS(this.provinceData)
        ] : [data];
    }
    @computed
    get cities() {
        let data = {
            code: '-1',
            name: '请选择'
        };
        return this.cityData ? [
            data,
            ...toJS(this.cityData)
        ] : [data];
    }
    @computed
    get districts() {
        let data = {
            code: '-1',
            name: '请选择'
        };
        return this.districtData ? [
            data,
            ...toJS(this.districtData)
        ] : [data];
    }

    @computed
    get enterpriseInfoData() {
        return this.enterpriseInfo && toJS(this.enterpriseInfo);
    }

    @computed
    get creditCodeFileListData() {
        return toJS(this.creditCodeFileList);
    }

    @computed
    get creditCodeFileData() {
        if (!this.creditCodeFile) {
            return null;
        }
        try {
            return toJS(JSON.parse(this.creditCodeFile));
        } catch (err) {
            return null;
        }
    }

    @computed
    get empowermentCodeFileData() {
        if (!this.empowermentCodeFile) {
            return null;
        }
        try {
            return toJS(JSON.parse(this.empowermentCodeFile));
        } catch (err) {
            return null;
        }
    }

    @computed
    get empowermentCodeFileListData() {
        return toJS(this.empowermentCodeFileList);
    }

    @computed
    get isSubmitBtnDisabled() {
        return !this.name ||
            !this.address ||
            !this.creditCode ||
            !this.mainBusiness ||
            !this.province_code || parseInt(this.province_code, 10) < 1 ||
            !this.city_code || parseInt(this.city_code, 10) < 1 ||
            !this.district_code || parseInt(this.district_code, 10) < 1;
    }

    @action
    reset() {
        this.errMsg.creditCode = '';
        this.isSuccess = false;
        this.globalErrMsg = '';
        this.enterpriseInfo = null;
        this.name = null;
        this.address = null;
        this.creditCode = null;
        this.mainBusiness = null;
        this.creditCodeFile = null;
        this.creditCodeFileList = null;
        this.empowermentCodeFile = null;
        this.empowermentCodeFileList = null;
        this.previewImageUrl = null;
        this.errMsg = {
            name: '',
            address: '',
            creditCode: '',
            mainBusiness: '',
            creditCodeFile: '',
            empowermentCodeFile: '',
        };
        [
            'provinceData',
            'province_code',
            'province_name',
            'cityData',
            'city_code',
            'city_name',
            'districtData',
            'district_code',
            'district_name',
        ].forEach(item => {
            this[item] = null;
        });
    }

    @action
    setUploadFileErr(name, msg) {
        this.errMsg[name] = msg;
    }

    @action
    validateField(field, fieldName) {
        const v = this[field].trim();
        if (!v) {
            if (['address', 'province_code', 'city_code', 'district_code'].indexOf(field) > -1) {
                this.errMsg.address = noticeMessage.inputEmpty(fieldName);
            } else {
                this.errMsg[field] = noticeMessage.inputEmpty(fieldName);
            }
            return false;
        }
        if (field === 'creditCode') {
            if (!validationUtil.isUniformSocialCreditCode(v)) {
                this.errMsg.creditCode = noticeMessage.inputFormatError('社会统一信用代码');
                return false;
            }
        }
        return true;
    }

    @action
    async init() {
        this.errMsg.creditCode = '';
        this.isSuccess = false;
        this.globalErrMsg = '';
        const res = await this.get('/user/enterprise-checks', null, {
            showGlobalLoading: true
        });
        runInAction(() => {
            const {
                code,
                data
            } = res;
            if (code === '0000' && data) {
                this.enterpriseInfo = data;
                if (data.check_status === 3) {
                    this.name = data.enterprise_name;
                    this.address = data.address;
                    this.creditCode = data.unified_social_credit_code;
                    this.mainBusiness = data.main_business;
                    let fileInfoStr = data.unified_social_credit_letter_code;
                    let fileInfo;
                    if (fileInfoStr) {
                        this.creditCodeFile = fileInfoStr;
                        try {
                            fileInfo = JSON.parse(fileInfoStr);
                        } catch (err) {
                            fileInfo = null;
                        }
                        if (fileInfo) {
                            this.creditCodeFileList = [{
                                uid: fileInfo.hash,
                                name: fileInfo.original,
                                status: 'done',
                                url: fileInfo.download,
                            }];
                        }
                    }
                    fileInfoStr = data.empowerment_code;
                    if (fileInfoStr) {
                        this.empowermentCodeFile = fileInfoStr;
                        try {
                            fileInfo = JSON.parse(fileInfoStr);
                        } catch (err) {
                            fileInfo = null;
                        }
                        if (fileInfo) {
                            this.empowermentCodeFileList = [{
                                uid: fileInfo.hash,
                                name: fileInfo.original,
                                status: 'done',
                                url: fileInfo.download,
                            }];
                        }
                    }

                    this.province_code = data.province_code;
                    this.province_name = data.province_name;
                    this.city_code = data.city_code;
                    this.city_name = data.city_name;
                    this.district_code = data.district_code;
                    this.district_name = data.district_name;
                    if (this.province_code) {
                        this.getCity(this.province_code);
                    }
                    if (this.city_code) {
                        this.getDistrict(this.city_code);
                    }
                }
                return;
            }
            this.enterpriseInfo = {};
        });
    }

    @action
    async getProvince() {
        const res = await this.get('/address/locations', {
            parent_code: 1
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.provinceData = res.data;
            }
        });
    }

    @action
    async getCity(v) {
        const res = await this.get('/address/locations', {
            parent_code: v
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.cityData = res.data;
            }
        });
    }

    @action
    async getDistrict(v) {
        const res = await this.get('/address/locations', {
            parent_code: v
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.districtData = res.data;
            }
        });
    }


    @action
    async submit() {
        this.globalErrMsg = '';
        if (!this.validateField('name', '企业名称') ||
            !this.validateField('address', '企业地址') ||
            !this.validateField('province_code', '省') ||
            !this.validateField('city_code', '市') ||
            !this.validateField('district_code', '区') ||
            !this.validateField('mainBusiness', '经营范围')
        ) {
            return;
        }
        const res = await this.post('/user/enterprise-checks', {
            address: this.address.trim(),
            empowerment_code: this.empowermentCodeFile,
            enterprise_name: this.name.trim(),
            main_business: this.mainBusiness.trim(),
            unified_social_credit_code: this.creditCode.trim().toUpperCase(),
            unified_social_credit_letter_code: this.creditCodeFile,
            province_code: this.province_code,
            province_name: this.province_name,
            city_code: this.city_code,
            city_name: this.city_name,
            district_code: this.district_code,
            district_name: this.district_name
        }, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            const code = res.code;
            if (code === '0000') {
                this.isSuccess = true;
            } else if (code === '1201') {
                this.globalErrMsg = '企业信息审核中，请不要重复提交';
            } else if (code === '1202') {
                this.globalErrMsg = '企业信息审核已通过，请不要重复提交';
            } else if (code === '1203') {
                this.errMsg.name = '该企业已经入驻，请联系平台';
            } else if (code === '1204') {
                this.errMsg.creditCode = '该社会统一信用代码已被使用，请联系平台';
            } else {
                this.globalErrMsg = '提交审核信息失败，请重试';
            }
        });
    }
}

export default new Store();